<template>
  <div class="page-main" v-title data-title="科技成果交易单">
    <home-nav :userData="userinfo"></home-nav>
    <div class="container" ref="imageWrapper">
      <div class="head-content">
        <span class="bold-font">科技成果交易单</span>
        <div class="btn-line">
          <a-button class="hte-btn" v-if="isSave"  :loading="btnLoading" @click="saveData">保存</a-button>
          <a-button class="hte-btn add-btn" type="primary" v-if="pushCpu" :loading="btnLoading" @click="onSubmitForm">推送</a-button>
        </div>
      </div>
      <div class="content">
        <a-form-model ref="ruleForm" :model="form" :rules="rules">
          <section>
            <div class="section-header">科技成果交易信息</div>
            <template>        
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="项目编号" prop="projectNo">
                    <a-input placeholder="点击选择项目" @click="associated.visible = true" v-model="form.projectNo" readOnly :disabled="!saveBtnShow || form.createType == 1"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="项目名称"> 
                    <a-input placeholder="自动取值" v-model="form.projectName" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="项目等级系数"> 
                    <a-input-number placeholder="自动取值" v-model="form.projectLevelRatio" disabled/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="项目状态" prop="projectStatusName">
                    <a-input placeholder="自动取值" v-model="form.projectStatusName" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="交易状态" prop="statusName">
                    <a-input placeholder="自动取值" v-model="form.statusName" disabled/>
                  </a-form-model-item>
                </a-col>
                  <a-col :span="8">
                  <a-form-model-item label="HBK定价流程号">
                    <a-input v-model="form.hbkNo"  placeholder="由HBK审核完成取值" disabled/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-tooltip :overlayStyle="{ width: '412px' }" overlayClassName="new-tooltip">
                  <template slot="title">
                    【科技成果名称】的命名原则：<br />                   
                    1、科学严谨，不使用口语化词语、简称、俗称、代称。<br />
                    2、精炼内容，提炼语言，且符合保密管理制度。<br />
                    3、尽可能不使用“产业化”及意思相近词语，特殊情况例外。
                  </template>
                  <a-col :span="16">
                    <a-form-model-item label="科技成果名称" prop="cgName">
                      <a-input v-model="form.cgName" maxlength="125" placeholder="请输入" :disabled="!saveBtnShow"/>
                    </a-form-model-item>
                  </a-col>
                </a-tooltip>
                <a-col :span="8">
                  <a-form-model-item label="成果交易单号">
                    <a-input v-model="form.cgNo" disabled/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="16">
                  <a-form-model-item label="交易甲方公司（投资方）" prop="cgCompanys">
                    <!-- <a-input v-model="form.cgCompany" maxlength="125" placeholder="请选择，可多选" :disabled="!saveBtnShow"/> -->
                    <a-select
                      mode="multiple"
                      :disabled="!saveBtnShow"
                      v-model="form.cgCompanys"
                      placeholder="请选择，可多选"                      
                      @change="(value, option)=>handleChange(value, option, 'cgCompany')"
                    >
                      <a-select-option v-for="(item, index) in dict.orderList5" :key="index" :value="item.code">
                        {{item.name}}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="甲方经营体（一级架构）" prop="firstPartyDepStr">                    
                    <!-- <a-select
                      show-search
                      mode="multiple"
                      v-model="form.cgCompanyLeaders"
                      placeholder="输入账号或者名称查找用户，可多选"
                      style="width: 100%"
                      :filter-option="false"
                      :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                      @search="val=>fetchUser(val,null,'userData')"
                      @change="(value, option)=>handleChange(value, option, 'cgCompanyLeader')"
                      :disabled="!saveBtnShow"
                    >
                      <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                      <a-select-option v-for="(d, index) in userData" :key="index" :value="d.username">
                        {{ d.realname }}
                      </a-select-option>
                    </a-select> -->
                    <std-select-depart name="甲方经营体（一级架构）" key="firstPartyDep" :multi="true" @change="(val)=>depChang(val,'firstPartyDeps')" @getName="(val)=>getDepName(val,'firstPartyDep')"  ref="firstPartyDep"
                    v-model="form.firstPartyDepStr" :parentConfig="{start:true,parentKey:'pid'}" :disabled="!saveBtnShow" :filterFirstDep="true"  :replaceFields="{children:'children', title:'title', key:'id', value: 'id' }">

                    </std-select-depart>
                  </a-form-model-item>
                </a-col>
              </a-row>
                <a-row :gutter="24">
                <a-col :span="16">
                  <a-form-model-item label="交易乙方公司" prop="pbCompanys">
                    <!-- <a-input v-model="form.cgCompany" maxlength="125" placeholder="请选择，可多选" :disabled="!saveBtnShow"/> -->
                    <a-select
                      mode="multiple"
                      :disabled="!saveBtnShow"
                      v-model="form.pbCompanys"
                      placeholder="请选择，可多选"                      
                      @change="(value, option)=>handleChange(value, option, 'pbCompany')"
                    >
                      <a-select-option v-for="(item, index) in dict.orderList5" :key="index" :value="item.code">
                        {{item.name}}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="乙方经营体（一级架构）" prop="secondPartyDepStr">                    
                    <!-- <a-select
                      show-search
                      mode="multiple"
                      v-model="form.investors"
                      placeholder="输入账号或者名称查找用户，可多选"
                      style="width: 100%"
                      :filter-option="false"
                      :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                      @search="val=>fetchUser(val,null,'userDataTz')"
                      @change="(value, option)=>handleChange(value, option, 'investor')"
                      :disabled="!saveBtnShow"
                    >
                      <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                      <a-select-option v-for="(d, index) in userDataTz" :key="index" :value="d.username">
                        {{ d.realname }}
                      </a-select-option>
                    </a-select> -->
                    <std-select-depart name="乙方经营体（一级架构）" key="secondPartyDep" :multi="true"  @change="(val)=>depChang(val,'secondPartyDeps')" @getName="(val)=>getDepName(val,'secondPartyDep')"  ref="secondPartyDep"
                    v-model="form.secondPartyDepStr" :parentConfig="{start:true,parentKey:'pid'}" :disabled="!saveBtnShow" :filterFirstDep="true" :replaceFields="{children:'children', title:'title', key:'id', value: 'id' }" >

                    </std-select-depart>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="交易类型" prop="tranType">
                    <a-select v-model="form.tranType" placeholder="请选择" @change="tranTypeChange" :disabled="!saveBtnShow">
                      <a-select-option v-for="(item, index) in dict.orderList0" :key="index" :value="item.code">
                        {{item.name}}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="交易加成率">
                    <a-input placeholder="根据交易类型决定" v-model="form.tranAddRate" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8" v-if="form.tranType != '1' && form.tranType != '2'">
                  <a-form-model-item label="效益贡献值" prop="gxValue">
                    <a-select v-model="form.gxValue" placeholder="请选择" :disabled="!saveBtnShow" @change="gxValueChange">
                      <a-select-option v-for="(item, index) in dict.orderList1" :key="index" :value="item.code">
                        {{item.name}}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8" v-if="form.tranType != '3' && form.tranType != '4'">
                  <a-form-model-item label="研发完全成本(万)" prop="yfMoney">
                    <a-input-number v-model="form.yfMoney" :precision="2"  :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
      :parser="value => value.replace(/\¥\s?|(,*)/g, '')" :disabled="!saveBtnShow" @change="tranPriceChange"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8" v-if="form.tranType != '2' && form.tranType != '3' && form.tranType != '4'">
                  <a-form-model-item label="资金占用成本(万)" prop="zjMoney">
                    <a-input-number v-model="form.zjMoney" :precision="2"  :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
      :parser="value => value.replace(/\¥\s?|(,*)/g, '')" :disabled="!saveBtnShow" @change="tranPriceChange"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="其他效益价值" prop="otherValues">
                    <a-select v-model="form.otherValues" mode="multiple" placeholder="请选择，可多选" :disabled="!saveBtnShow" @change="(value, option)=>handleChange(value, option, 'otherValue')">
                      <a-select-option v-for="(item, index) in dict.orderList4" :key="index" :value="item.code">
                        {{item.name}}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" v-if="form.tranType == '3'">
                <a-col :span="8">
                  <a-form-model-item label="新品销值(万)" prop="newSales">
                    <a-input-number v-model="form.newSales" :precision="2"  :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
      :parser="value => value.replace(/\¥\s?|(,*)/g, '')" :disabled="!saveBtnShow" @change="tranPriceChange"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="新品毛利(万)" prop="newMl">
                    <a-input-number v-model="form.newMl" :precision="2"  :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
      :parser="value => value.replace(/\¥\s?|(,*)/g, '')" :disabled="!saveBtnShow" @change="tranPriceChange"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24" v-if="form.tranType == '4'">
                <a-col :span="8">
                  <a-form-model-item label="旧技术成本(万)" prop="oldTechCost">
                    <a-input-number v-model="form.oldTechCost" :precision="2"  :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
      :parser="value => value.replace(/\¥\s?|(,*)/g, '')" placeholder="请输入" @change="techCostChange('oldTechCost')" :disabled="!saveBtnShow"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="新技术成本(万)" prop="newTechCost">
                    <a-input-number v-model="form.newTechCost" :precision="2"  :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
      :parser="value => value.replace(/\¥\s?|(,*)/g, '')" placeholder="请输入" @change="techCostChange('newTechCost')" :disabled="!saveBtnShow"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="技术改进效益(万)">
                    <a-input-number v-model="form.techChangeValue" :precision="2"  :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
      :parser="value => value.replace(/\¥\s?|(,*)/g, '')" placeholder="自动计算，旧技术成本-新技术成本" disabled/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="技术应用期限" prop="techAppTerm">
                    <a-input-number v-model="form.techAppTerm" placeholder="单位年" @change="techProfitChange('techAppTerm')" :disabled="!saveBtnShow"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="技术迭代周期" prop="techIterTerm">
                    <a-input-number v-model="form.techIterTerm" placeholder="单位年" @change="techProfitChange('techIterTerm')" :disabled="!saveBtnShow"/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="专利保护期限" prop="techProtectTerm">
                    <a-input-number v-model="form.techProtectTerm" placeholder="单位年" @change="techProfitChange('techProtectTerm')" :disabled="!saveBtnShow"/>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col :span="8">
                  <a-form-model-item label="技术收益期限">
                    <a-input-number v-model="form.techProfitTerm" placeholder="自动计算取值" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="交易价格(万)">
                    <a-input-number v-model="form.tranPrice" :precision="2"  :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
      :parser="value => value.replace(/\¥\s?|(,*)/g, '')" placeholder="根据条件自动计算" disabled/>
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item label="审核交易价格(万)">
                    <a-input-number v-model="form.tranPriceAudit" :precision="2"  :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
      :parser="value => value.replace(/\¥\s?|(,*)/g, '')" placeholder="由HBK审核完成取值" disabled/>
                  </a-form-model-item>
                </a-col>
              
                
              </a-row>
            </template>   
            <template>
              <div class="section-header mt15">
                <div>附件上传<span class="em">必须上传附件才能提交流程，请下载模板填写《研发完全成本表》《经济效益核算表》，然后上传附件。</span></div>
              </div>
              <div class="section-table">
                 
                <div class="btn-line">
                  <commonAttachDownload ref="downloader" busKey="1"></commonAttachDownload>
                  <template>
                    <ht-upload
                      v-if="attachShow"
                      v-show="showFileBtn"
                      ref="myUpload"
                      class="upload-demo"
                      multiple
                      dbKey="Trd"
                      busField="cgAttach"
                      busType=""
                      :busKey="!!form.id? form.id.toString(): form.projectBuildId "
                      ftpKey="ftp"
                      v-model="fileData"
                      :show-file-list="false"
                      :before-upload="(value) => beforUpload(value, 'fileData')"
                    >
                      <a-button class="hte-btn add-btn" v-if="isAttach" type="primary" icon="plus">上传</a-button>
                    </ht-upload>                    
                  </template>
                  <a-button class="hte-btn" v-if="attachShow" @click="handAction('download')">下载</a-button>
                  <a-button class="hte-btn" v-if="isAttach"  @click="handAction('del')" v-show="showFileBtn">删除</a-button>
                </div>
                <div>
                 <a-tooltip :overlayStyle="{ width: '412px' }" overlayClassName="new-tooltip">
                  <template slot="title">
                    附件上传原则：<br />                   
                    1、技术转让、受托开发：必须上传《研发完全成本表》。<br />
                    2、技术授权（新产品）、技术授权（产品改良）：必须上传《经济效益核算表》。
                  </template>
                  <a-table
                    class="hte-table-content"
                    :columns="fileColumns"
                    :data-source="fileData"
                    :pagination="false"
                    :loading="btnLoading"
                    rowKey="id"
                    :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                    bordered
                    size="middle"
                  >
                  <template slot="fileName" slot-scope="text, record">
                  <template>
                    <a @click="showAttach(record)">{{ record.fileName }}</a>
                  </template>
                </template>
                  </a-table>
                </a-tooltip>
                  
                </div>

              </div>
            </template>  
                   
          </section>     
          
        </a-form-model>
        <div class="btn-bottom-fixed">
          <a-button class="hte-btn" v-if="isSave" :loading="btnLoading" @click="saveData">保存</a-button>
          <a-button class="hte-btn add-btn" type="primary" v-if="pushCpu" :loading="btnLoading" @click="onSubmitForm">推送</a-button>
        </div>
      </div>
    </div>
    <pagination-select
      :title="associated.title"
      :searchPlaceholder="associated.searchPlaceholder"
      :visible="associated.visible"
      :url="associated.url"
      :params="associated.params"
      actionType="postAction"
      :columns="associated.columns"
      @hatchHandleOk="associatedHandleOk"
    />
  </div>
</template>
<script>
const validateChinese = (rule, value, callback) => {
  let reg = /[\u4e00-\u9fa5]/g
  if (!reg.test(value)) {
    callback('订单名称必须包含中文')
  } else {
    callback()
  }
};
import {getAction, postAction, previewAttach} from '@/api/manage';
import Vue from 'vue';
import '@/utils/upload.install.js';
import '@/config/hteupload.install.js';
import {ACCESS_TOKEN, USER_NAME} from '@/store/mutation-types'
import {codeInfoList,codeInfoByTypeAndParent} from '@/api/codeInfo'
import {Modal} from 'ant-design-vue'
import { endWith, formatFileSize } from '@/utils/common.js'
import {formatSize, isPreview} from '@/components/hteUpload/common/utils'
import {downloadAttach} from '@/components/hteUpload/api/upload'
import {Base64} from 'js-base64'
import {filterHasPermission} from '@/utils/hasPermission'

export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),    
    htApproval: () => import('@/config/ht-approval.umd.min.js'),
    PaginationSelect: () => import('@/components/tools/PaginationSelect'),
    commonAttachDownload:()=> import('@/components/tools/commonAttachDownload'),
     stdSelectDepart:()=> import('@/views/library/stdSample/StdSelectDepart'),
  },
  data() {
    return {      
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'TechResultOrderInfo',
      },
      id:this.$route.query.id,
      projectBuildId:this.$route.query.projectBuildId,
      createType: this.$route.query.createType,
      options: {
        userId: Vue.ls.get(USER_NAME),
      },
      dict: {
        orderList0: [], // 交易类型
        orderList1: [], // 效益贡献值
        orderList2: [],
        orderList3: [], // 成果项目类型
        orderList4: [], // 其他效益价值
        orderList5: [], // 项目需求公司
        // orderList6: [], 
      },
      form: {},
      btnLoading:false,
      saveBtnShow: true,    // true 编辑状态   
      isShowPushBtn: false, // 是否显示推送按钮
      rules: {
        projectNo: [{ required: true, message: '请选择项目', trigger: 'change',},],
        cgName: [{ required: true, message: '请输入订单名称', trigger: 'blur'},
          { min: 3, max: 120, message: '订单名称3个字符以上，120个字符以内', trigger: 'blur' },
          // { validator: validateChinese, trigger: 'blur' },
        ],
        cgCompanys: [{ required: true, message: '请选择交易甲公司', trigger: 'change',},],
        firstPartyDepStr: [{ required: true, message: '请选择甲方经营体', trigger: 'change',},],
        pbCompanys: [{ required: true, message: '请选择交易已公司', trigger: 'change',},],
        secondPartyDepStr: [{ required: true, message: '请选择乙方经营体', trigger: 'change',},],
        tranType: [{ required: true, message: '请选择交易类型', trigger: 'change',},],
        gxValue: [{ required: true, message: '请选择效益贡献值', trigger: 'change',},],        
        yfMoney: [{ required: true, message: '请输入', trigger: 'blur',},],
        zjMoney: [{ required: true, message: '请输入', trigger: 'blur',},],        
        otherValues: [{ required: true, message: '请选择其他效益价值', trigger: 'change',},],
        newSales: [],
        newMl: [],
        oldTechCost: [],
        newTechCost: [],
        techAppTerm: [{ required: true, message: '请输入', trigger: 'blur'}],
        techIterTerm: [{ required: true, message: '请输入', trigger: 'blur'}],
        techProtectTerm: [{ required: true, message: '请输入', trigger: 'blur'}],
      },      
      // 附件上传
      fileColumns: [
        {title: '附件名称',dataIndex: 'fileName',scopedSlots: { customRender: 'fileName' }},
        {title: '文件大小',dataIndex: 'size',width: 150,align: 'center',customRender:function (text) {return formatSize(text)}},
        {title: '上传人',dataIndex: 'uploaderName',width: 150,align: 'center',},
        {title: '上传时间',dataIndex: 'uploadTime',width: 230,align: 'center',},        
      ],
      fileData: [],
      showFileBtn:true,
      selectedRowKeys: [],  
      selectionRows: [],
      url: {
        queryOrderById:'projectBuild/ProjectBuildCg/queryCgInfo',
        saveOrder:'/projectBuild/ProjectBuildCg/saveCg',        
        getUserList: '/lib/hteFileClass/getUserListOnlyUpms',        
        // submitOrder:'/projectBuild/ProjectBuildCg/pushHbk',
        downLoadBatch:'/common/downLoadBatchWithFileName', // 下载
        getMouldAttachId:"/hteLibMediaOrder/getMouldAttachId",   // 下载模板   
        cpuData :'projectBuild/ProjectBuildCg/cpuData',//计算数据  
        queryBuildById: '/projectBuild/getNormalVo',
      },
      // 项目单
      associated: {
        visible: false,
        title: '请选择项目',
        searchPlaceholder: '输入项目编号或名称查询',
        url: '/projectBuild/ProjectBuildCg/queryFindProjectByCg',
        params: {
          projectClass: '10',
          projectTypeSubCategory: ''
        },
        columns: [
          {
            title: '项目编号',
            dataIndex: 'projectNo',
            align: 'center',
          },
          {
            title: '项目名称',
            dataIndex: 'projectName',
            align: 'center',
          },
        ],
      },
      // 交易公司领导
      fetching: false,
      userData: [],
      userDataTz:[],
      flag:false,
      projectBuildData:{}
    }
  },
  mounted() {    
    this.initDics();
    this.initOrder();
    // if(!this.createType){
    //   // this.form.applyUserId=this.userinfo.info.username;
    //   // this.form.applyUserName=this.userinfo.info.realname;
    //   // this.form.applyDeptId=this.userinfo.info.deptId;
    //   // this.form.applyDeptName=this.userinfo.info.deptName;
    //   // this.form.projectName=this.form.applyUserName+'/'+this.form.applyDeptName;
    //   // this.saveBtnShow=true;      
    // }else{
    //   this.initOrder(this.projectBuildId);
    // }
    // 只有入口是[科技成果交易表]才会显示推送
    // if(this.id){
    //   this.isShowPushBtn = true
    // }
  },
  computed:{
    isManage(){
      var isManage = false
      if(!!this.form.projectManagerId){
        var manage = this.form.projectManagerId.split(",")
        isManage = manage.some(i=>{return i ==  this.userinfo.info.username})
      }
      return isManage
    },
    isSave(){
      var isSave =  !this.form.id || (this.form.status < 2 &&  (this.form.createUserId == this.userinfo.info.username || this.isManage))
      if(this.form.createType == 2){
        isSave = isSave && filterHasPermission('tcg:edit')
      }
      this.saveBtnShow = isSave
      return isSave
    },
    pushCpu(){
       var isShowPushBtn = this.isSave && this.form.createType == 2 && !!this.form.id
       if(this.isSave && this.form.projectStatus>2 && this.form.createType == 1 ){
          isShowPushBtn = true
       }
       this.isShowPushBtn = isShowPushBtn
       return isShowPushBtn
    },
    attachShow(){
      return !!this.form.projectBuildId && (this.projectBuildData.projectSubTypeAdmin || this.projectBuildData.isProjectManager || this.projectBuildData.isBuildAuditor)
       if(this.form.createType == 1){
        return !!this.form.projectBuildId
      }else{
        return  !!this.form.id
      }
    },
    isAttach(){
     return this.isSave && this.attachShow
    }
  },
   watch: {
    
  },
  methods: {
    /**
     * 字典 
     */
    initDics(){
      const list = ['成果交易类型', '成果效益贡献值', '成果项目等级系数', '成果项目类型', '成果其他效益价值', '项目需求公司']
      list.forEach((item, index)=>{
        codeInfoList({type:item,pageSize:-1,isdel: 0,column:"code",order:"Asc"}).then((res) => {
          if (res.code == 200) {
            this.dict['orderList'+ index] = res.result.records
            if(item == '成果项目类型'){
              const x = res.result.records.map(item=>{return item.code})
              this.associated.params.projectTypeSubCategory = x.join(',')
            }
          } else {
            this.$message.warning('操作异常:' + res.message)
          }
        })
      })      
    },
    tranTypeChange(value){
      const find = this.dict.orderList0.find(item=>{return item.code === value})
      this.$set(this.form,'tranAddRate', find.parentid);  
      this.setlLinkage();      
    },
    gxValueChange(value){
      const find = this.dict.orderList1.find(item=>{return item.code === value})
      this.$set(this.form,'gxValueRate', find.parentid);
      this.tranPriceChange()
    },
    setlLinkage(type){
      if(this.form.tranType == '3'){
        this.rules.newSales = [{ required: true, message: '请输入', trigger: 'blur'},]
        this.rules.newMl = [{ required: true, message: '请输入', trigger: 'blur'},]
      }else{
        // this.$set(this.form,'newSales', '');  
        // this.$set(this.form,'newMl', '');  
        this.rules.newSales = []
        this.rules.newMl = []
      }
      if(this.form.tranType == '4'){
        this.rules.oldTechCost = [{ required: true, message: '请输入', trigger: 'blur'},]
        this.rules.newTechCost = [{ required: true, message: '请输入', trigger: 'blur'},]
      }else{
        // this.$set(this.form,'oldTechCost', '');  
        // this.$set(this.form,'newTechCost', '');  
        // this.$set(this.form,'techChangeValue', '');  
        this.rules.oldTechCost = []
        this.rules.newTechCost = []
      }
      if(!type){
        this.tranPriceChange();
      }      
    },
    /**
     * 自动取值 
     */
    techCostChange(type){
      // 【技术改进效益(万)】的值等于【旧技术成本(万)】减【新技术成本(万)】自动得出      
      if(typeof this.form.oldTechCost != 'number' || typeof this.form.newTechCost != 'number') {
        this.$set(this.form, 'techChangeValue', null)
        this.tranPriceChange()
        return
      }
      const num = Number(this.form.oldTechCost) - Number(this.form.newTechCost)
      this.$set(this.form, 'techChangeValue', num)
      this.tranPriceChange()
    },
    techProfitChange(type){
      // 【技术收益期限】取【技术应用期限】【技术迭代周期】【专利保护期限】3个值中的最小值     
      if(typeof this.form.techAppTerm != 'number' || typeof this.form.techIterTerm != 'number' || typeof this.form.techProtectTerm != 'number') {
        this.$set(this.form, 'techProfitTerm', null)
        return
      }
      let min = Math.min(...[this.form.techAppTerm, this.form.techIterTerm, this.form.techProtectTerm]);      
      this.$set(this.form, 'techProfitTerm', min)
    },
    tranPriceChange(){
      // 1）技术转让：【交易价格】=[【研发完全成本】*(1+0.30*项目等级系数)]/交易公司数量+【资金占用成本】；
      // 2）受托开发：【交易价格】=【研发完全成本】*(1+0.22*项目等级系数)；
      // 3）技术授权(新产品)：【交易价格】=Min{【新品销值】*0.05*项目等级系数，【新品毛利】*【效益贡献值】*项目等级系数}；
      // 4）技术授权(产品改良)：【交易价格】=【技术改进效益】*【效益贡献值】*项目等级系数。
      let price = 0
      this.cpuData()
      return
      if(typeof this.form.projectLevelRatio != 'number'){
        this.$set(this.form, 'tranPrice', null)
        return 
      }
      switch(this.form.tranType) {
        case '1':
          if(typeof this.form.yfMoney != 'number' || typeof this.form.zjMoney != 'number' || !this.form.cgCompanys){
            price = null
          }else{
            price = (this.form.yfMoney * (1+0.30*this.form.projectLevelRatio)) / this.form.cgCompanys.length + this.form.zjMoney
          }          
          break;
        case '2':
          if(typeof this.form.yfMoney != 'number'){
            price = null
          }else{
            price = this.form.yfMoney * (1+0.22*this.form.projectLevelRatio)
          }          
          break;
        case '3':
          if(typeof this.form.newSales != 'number' || typeof this.form.newMl != 'number' || !this.form.gxValueRate){
            price = null
          }else{
            price = Math.min(...[this.form.newSales*0.05*this.form.projectLevelRatio, this.form.newMl*this.form.gxValueRate*this.form.projectLevelRatio])
          }            
          break;
        case '4':
          if(typeof this.form.techChangeValue != 'number' || !this.form.gxValueRate){
            price = null
          }else{
            price = this.form.techChangeValue*this.form.gxValueRate*this.form.projectLevelRatio
          }          
          break; 
        default:
          price = null
          break 
      }
      this.$set(this.form, 'tranPrice', price)
    },
    //后台计算数据
    cpuData(type = 1){
      postAction(this.url.cpuData,this.form).then(res=>{
        if(res.code == 200){
          var result = res.result
          this.$set(this.form, 'projectLevelRatio', result.projectLevelRatio)
          this.$set(this.form, 'tranPrice', result.tranPrice)
        }
      })
    },
    /**
     * 初始查询 
     */
    initOrder(id){
      var param = {}
      if(!!this.id){
          param.id = this.id
      }else if(!!this.projectBuildId){
          param.projectBuildId = this.projectBuildId
      }else{
        param = {id:'-1'}
      }
      getAction(this.url.queryOrderById, param).then((res) => {
        if (res.code == 200) {
          var result = res.result
          result.cgCompanys = !result.cgCompanys?[]:result.cgCompanys
          result.pbCompanys = !result.pbCompanys?[]:result.pbCompanys
          result.cgCompanyLeaders = !result.cgCompanyLeaders?[]:result.cgCompanyLeaders
          result.firstPartyDeps = !result.firstPartyDeps?[]:result.firstPartyDeps
          result.secondPartyDeps = !result.secondPartyDeps?[]:result.secondPartyDeps
          result.otherValues = !result.otherValues?[]:result.otherValues
          if(!this.id && !!result.id){
              this.$router.push({ path: '/blank', query: {reload : '1', backUrl: encodeURI('/techResult/addOrder?id='+result.id )} })
              return
          }
          this.form = result; 
          if(!result.id){
            this.form.createType = this.createType
            if(!!this.projectBuildId){
              this.form.projectBuildId = this.projectBuildId
              this.initProject()
            }
            
          } 
          if (this.form.cgCompanyLeaders) {
            this.fetchUser(result.cgCompanyLeaders.join(','), 'init','userData')
          }
          this.$set(this.form,'firstPartyDepStr',result.firstPartyDeps.join(','))
          this.$set(this.form,'secondPartyDepStr',result.secondPartyDeps.join(','))
          if(['3', '4'].includes(this.form.tranType)){
            this.setlLinkage('init')
          }
          this.getProjectBuildData()
        } else {
          this.$message.warning('查询失败:' + res.message)
        }
      })
    },   
    getProjectBuildData: function () {
        getAction(this.url.queryBuildById, {id: this.form.projectBuildId}).then(res => {
          this.projectBuildData = res.result || {};
        })
      }, 
    /**
     * 交易公司领导 / 成果交易公司 / 其他效益价值
     */
     fetchUser(val, type,key) {
      if (val) {
        this[key] = []
        this.fetching = true
        let params = {}
        if(type == 'init'){
          params ={nameList: val}
        }else{
          params = {name: val} 
        }
        getAction(this.url.getUserList, params).then((res) => {
          if (res.success) {
            this[key] = res.result
            this.fetching = false
          }
        })
      }
    },
     getDepName(name,key){
         this.$set(this.form,key,name)
      },
      depChang(val,key){
        this.$set(this.form,key, !!val? val.split(','):[])
      },
    handleChange(value, option, targe) {      
      let arr = []
      option.forEach((item) =>
        arr.push(!!item.componentOptions.children && item.componentOptions.children.length >0 && item.componentOptions.children[0].text ? item.componentOptions.children[0].text.trim() : '')
      )      
      this.$set(this.form, targe, arr.join(','))
      if(targe == 'cgCompany'){
        this.tranPriceChange()
      }
    },    
    /**
     * 选择项目单
     */
    associatedHandleOk(record) {
      if (record != null && record.length > 0) {        
        // this.initOrder(record[0].id);
        this.$set(this.form,'projectLevel',record[0].projectLevel)
        this.$set(this.form,'projectBuildId',record[0].projectBuildId)
        this.$set(this.form,'projectName',record[0].projectName)
        this.$set(this.form,'projectNo',record[0].projectNo)
        this.$set(this.form,'projectStatusName',record[0].projectStatusName)
        this.$set(this.form,'projectStatus',record[0].projectStatus)
        this.$set(this.form,'projectManagerId',record[0].projectManagerId)
        this.$set(this.form,'projectManager',record[0].projectManager)
        this.$set(this.form,'factory',record[0].factory)
        this.$set(this.form,'factoryName',record[0].factoryName)
        this.$set(this.form,'factoryCode',record[0].factoryCode)
        this.$set(this.form,'projectTypeSubCategory',record[0].projectTypeSubCategory)
      }
      this.associated.visible = false
      this.cpuData()
    },
    initProject(){
      postAction(this.associated.url,{projectBuildId:this.form.projectBuildId}).then(res=>{
        if(res.code == 200){
          if(!res.result.records || res.result.records.length == 0){
            this.$message.error('项目不存在,请您重新选择！')
            return
          }
          this.associatedHandleOk(res.result.records)
        }else{
          this.$message.error(res.msg);
        }
      })
    },
    /**
     * 上传附件 
     */
    beforUpload(file, type){      
      const that = this;
      let fileName= file.name 
      const flag = this[type].some(item=>{
        return item.fileName == fileName
      })
      if(flag){
        that.$message.warning(`【${fileName}】文件名重复`);
        return false
      }
      return true
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },

    /**
     * 操作 
     */
    handAction(type){      
      if(type == 'downloadMould'){
        // 下载模板
        // this.downLoadMould();
      }
      if(type == 'download'){
        // 下载
        if(this.selectionRows.length == 0){
          this.$message.warning('请选择至少一条数据！');
          return;
        }
        let attachIds=this.selectedRowKeys.join(",");
        this.doDownLoadBatch(attachIds);
      }
      if(type == 'del'){
        // 删除        
        if(this.selectionRows.length == 0){
          this.$message.warning('请选择至少一条数据！');
          return;
        }
        const that = this;
        // if(this.selectionRows.some(f=>f.uploader!=that.options.userId)){
        //   this.$message.warning('只能删除自己上传的附件！');
        //   return;
        // }
        Modal.confirm({
          title: '请确认是否删除此附件?',          
          onOk: function() {
            for (let i = that.selectionRows.length - 1; i > -1; i--) {
              const rowIndex = that.selectionRows[i] ;
              const obj = that.selectionRows.find(item=>item.id == rowIndex.id)
              that.$refs['myUpload'].delete(obj);
            }  
            that.selectedRowKeys = []
          }
        });
      }
    },
    downLoadMould(){
      getAction(this.url.getMouldAttachId, {tranType:this.form.tranType}).then((res) => {
        if (res.code == 200) {
          if(!res.result){
            this.$message.warning('没有相应的模板，请联系系统管理员维护');
            return;
          }
          let url=this.HTE_OLD_SERVER_URL+`/projectContractMould/download?bootToken=${Vue.ls.get(ACCESS_TOKEN)}&id=`+res.result;
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
        } else {
          this.$message.warning('获取模板失败:' + res.message)
        }
      }).catch((res) => {
        this.$message.warning('获取模板失败:' + res.message)
      })
    },
    doDownLoadBatch(attachIds) {
      if (document.getElementById('_attachToolView_downloadfile_frame') == null) {
        var downloadFrame = $('<iframe id="_attachToolView_downloadfile_frame" style="display: none"></iframe>')
        downloadFrame.appendTo($('body'))
      }
      var iframe = document.getElementById('_attachToolView_downloadfile_frame');
      iframe.src = this.API_BASE_URL +
        this.url.downLoadBatch +
        '?attachIds=' +
        attachIds +
        '&dbKey=Trd&ftpKey=ftp&token=' +
        Vue.ls.get(ACCESS_TOKEN)+'&zipFileName='+encodeURIComponent(this.form.projectNo+'附件.zip');
    },
    //校验信息
     checkData(callback){
       const vm = this
      vm.$refs.ruleForm.validate(
          (valid)=>{
            if(valid){
              if(!vm.fileData.length){
              vm.$message.warning(` 附件上传原则：               
                    1、技术转让、受托开发：必须上传《研发完全成本表》。
                    2、技术授权（新产品）、技术授权（产品改良）：必须上传《经济效益核算表》。`);
              
              return false;
            }            
            // if([1,2].some(i=>{return vm.form.tranType == i})  ){
            //   const flag1 = vm.fileData.some(item=>{
            //   return item.name == '研发完全成本表.xlsx'
            //   })
            //   if(!flag1){
            //     vm.$message.warning(`请先上传《研发完全成本表》附件`);
            //   return false;
              
            //   } 
            // }else{
            //   const flag2 = vm.fileData.some(item=>{
            //     return item.name == '经济效益核算表.xlsx'
            //   })
            //   if(!flag2){
            //     vm.$message.warning(`请先上传《经济效益核算表》附件`);
            //     return false;
            //   }
            // }
            
            
            callback()
          }else{
              return false;
          }

      })
        
    },
    /**
     * 推送 
     */
     onSubmitForm() {
      const vm = this
        function callback() {  
        
          var param =JSON.parse(JSON.stringify( vm.form)) 
          param.status = 2
          postAction(vm.url.saveOrder, param).then((res) => {
            vm.btnLoading=false;
            if (res.code == 200) {
              vm.$message.success(`推送成功`);
              vm.initOrder(vm.form.id);
            } else {
              vm.$message.warning('推送失败:' + res.message)
            }
          })
      } 
      vm.checkData(callback)
    
    },
    /**
     * 保存
     *  
     */
    saveData(){
       const vm = this
      if(!this.form.projectNo){
        this.$message.warning(`请先选择项目编号`);
        return
      }
      if(!this.form.cgName){
        this.$message.warning(`请先填写成果名称`);
        return
      }
      function callback(){
        vm.btnLoading=true;
        postAction(vm.url.saveOrder, vm.form).then((res) => {
          vm.btnLoading=false;
          if (res.code == 200) {
            vm.$message.success(`保存成功`);
            if(!vm.form.id){
              vm.$router.push({ path: '/blank', query: {reload : '1', backUrl: encodeURI('/techResult/addOrder?id='+res.result.id )} })
            }else{
              vm.initOrder()
            }
            
          } else {
            vm.$message.warning('保存失败:' + res.message)
          }
        })
      }
      //先放开
      if(!vm.form.id){
          vm.form.attachments = vm.fileData
      }
      vm.checkData(callback)
      return
      //项目创建的校验全部信息
      if(vm.form.createType == 1){
        if(!vm.form.id){
              vm.form.attachments = vm.fileData
          }
         vm.checkData(callback)
          
      }else{
        callback()
      }
        
    },
    showAttach(record) {
      var id = record.id
      var fileName = record.fileName
      //以rar、zip、dwg结尾的文件，直接下载不预览
      if (
        endWith(fileName, 'rar') ||
        endWith(fileName, 'zip') ||
        endWith(fileName, 'dwg') ||
        endWith(fileName, 'tgz')
      ) {
        this.$emit('afterDown', [record])
        this.doDownLoadBatch(id)
        return
      }
      let params = {
        id: id,
        ftpKey: 'ftp',
      }
      previewAttach(params)
        .then((result) => {
          const url = URL.createObjectURL(result)
          window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + url)
        })
        .catch((err) => {
          this.$message.warning('下载文件失败')
        })
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.cr-content-pop {
  p {margin-bottom: 15px;color: #666;
    &:hover{color: @bg-color-btn;}
    &:last-child {
      margin-bottom: 0;
    }
  }
}
.em{font-size: 12px;color: #f5222d;margin-left: 5px;}
/deep/ .ant-input-number{width: 100%;}
.mt15{margin-top:25px}
.ratebox{top: -3px;display: inline-block;}
.btn-line{display: flex;}
/deep/ .ant-form .ant-form-item:not(.self-form-item) .ant-form-item-label{width: 149px;}
/deep/ .ant-form .ant-form-item:not(.self-form-item) .ant-form-item-control-wrapper{width: calc(100% - 149px);}
.new-tooltip {
  min-width: 410px !important;
}
</style>
